package com.jason.bookworm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jason.bookworm.response.StatusEnum;
import com.jason.bookworm.exception.ServiceException;
import com.jason.bookworm.dao.mapper.UserMapper;
import com.jason.bookworm.dao.pojo.User;
import com.jason.bookworm.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service    //业务层方法须以@Service注解标记
public class UserServiceImpl implements UserService {
    @Autowired  //通过@Autowired注解拿到UserMapper的实现类
    private UserMapper userMapper;

    //注册新读者
    @Override
    public void registerReader(User user) {
        //判断用户名和密码是否为空
        if(user.getUsername().isEmpty()||user.getPassword().isEmpty()){
            throw new ServiceException(StatusEnum.Register_ERR,"用户名或密码不存在！");
        }
        //判断用户名是否存在
        QueryWrapper<User>queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("u_username",user.getUsername());
        User user1 = userMapper.selectOne(queryWrapper);
        //如果存在则抛出自定义异常
        if(user1!=null){
            throw new ServiceException(StatusEnum.PUT_ERR,"该用户已存在！请重新设置用户名。");
        }
        userMapper.insert(user);
    }

    //注册新管理员
    @Override
    public void registerManager(User user,String privilege) {
        //修改用户权限
        user.setPrivilege(privilege);
        registerReader(user);
    }

    @Override
    public List<User> getAllUser() {
        return userMapper.selectList(null);
    }

    @Override
    public User getOneUser(String username) {
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("u_username",username);
        return userMapper.selectOne(queryWrapper);
    }

    @Override
    public void updateUser(User user) {
        userMapper.updateById(user);
    }

    @Override
    public void deleteUser(User user) {
        userMapper.deleteById(user);
    }


}
